package com.wulian.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;


public final class FileUtil {
	private static Logger logger = LoggerFactory.getLogger(FileUtil.class);

	public static void compressFiles(File[] files, String zipFileName,
			boolean needClear) {
		File targetFile = new File(zipFileName);
		if (targetFile.exists()) {
			logger.warn("压缩文件已存在，重新命名");
			compressFiles(files, zipFileName + "-new.zip", needClear);
		} else {
			ZipOutputStream outputStream = null;
			try {
				outputStream = new ZipOutputStream(new FileOutputStream(
						targetFile));
				outputStream.setLevel(9);
				for (int i = 0; i < files.length; i++) {
					File tempFile = files[i];
					if (tempFile.isDirectory()) {
						logger.warn("压缩文件不能为文件夹");
						continue;
					}
					ZipEntry entry = new ZipEntry(tempFile.getName());
					outputStream.putNextEntry(entry);
					InputStream inputStream = new FileInputStream(tempFile);
					byte[] buffer = new byte[4096];
					int t = 0;
					while ((t = inputStream.read(buffer)) != -1) {
						outputStream.write(buffer, 0, t);
					}
					closeInputStream(inputStream);
				}
				outputStream.close();
				logger.debug("压缩文件成功!");
			} catch (FileNotFoundException e) {
				logger.warn("指定文件不存在", e);
			} catch (ZipException e) {
				logger.warn("压缩文件失败或没有找到被压缩文件", e);
			} catch (IOException e) {
				logger.error("IO错误", e);
			} finally {
				closeOutputStream(outputStream);
			}

			if (needClear) {
				for (int i = 0, iLength = files.length; i < iLength; i++) {
					File file = files[i];
					if (file.exists() && file.isFile()) {
						file.delete();
						logger.debug("删除文件" + file.getName() + "成功");
					}
				}
			}
		}
	}

	public static boolean moveFile(File file, File targetDir) {
		if (file == null)
			return false;
		if (targetDir == null) {
			logger.error("目标文件夹不能为空");
			return false;
		}
		if (!targetDir.exists())
			targetDir.mkdir();
		if (!targetDir.isDirectory()) {
			logger.warn("移动目标不是文件夹");
			return false;
		}
		FileOutputStream out = null;
		FileInputStream input = null;
		try {
			out = new FileOutputStream(new File(targetDir, file.getName()));
			input = new FileInputStream(file);
			byte[] buffer = new byte[4096];
			int r = 0;
			while ((r = input.read(buffer)) != -1) {
				out.write(buffer, 0, r);
			}
			out.flush();
		} catch (FileNotFoundException e) {
			logger.error("指定文件未找到", e);
		} catch (IOException e) {
			logger.error("IO错误", e);
		} finally {
			closeOutputStream(out);
			closeInputStream(input);
		}
		return file.delete();
	}

	public static void closeInputStream(InputStream in) {
		if (in != null) {
			try {
				in.close();
			} catch (IOException e) {
				logger.warn("关闭输入流失败", e);
			} finally {
				in = null;
			}
		}
	}

	public static void closeOutputStream(OutputStream out) {
		if (out != null) {
			try {
				out.close();
			} catch (IOException e) {
				logger.warn("关闭输出流失败", e);
			} finally {
				out = null;
			}
		}
	}

	public static final boolean fileIsCanHold(File file) {
		// File file = new File(fileName);
		if (file.exists()) {
			long size = file.length();
			long md = file.lastModified();
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				return false;
			}
			if (!((file.length() == size) && (md == file.lastModified()))) {
				return false;
			}

			RandomAccessFile accessFile = null;
			try {
				accessFile = new RandomAccessFile(file, "rw");
			} catch (FileNotFoundException e1) {
				return false;
			} finally {
				try {
					if (accessFile != null)
						accessFile.close();
				} catch (IOException e) {

				}
			}
			return true;
		}
		return false;
	}
	
	
	/**保存文件
     * @param stream
     * @param path
     * @param filename
     * @throws IOException
     */
    public static void SaveFileFromInputStream(InputStream stream,String path,String filename) throws IOException
    {      
        FileOutputStream fs=new FileOutputStream( path + "/"+ filename);
        byte[] buffer =new byte[1024*1024];
        int bytesum = 0;
        int byteread = 0; 
        while ((byteread=stream.read(buffer))!=-1)
        {
           bytesum+=byteread;
           fs.write(buffer,0,byteread);
           fs.flush();
        } 
        fs.close();
        stream.close();      
    }       
    
    
    /**
     * 如果文件夹不存在，则创建文件夹
     * @param savePath
     * @return
     */
    public static File fileIsMkdirs(String savePath){
    	 File saveFile = new File(savePath);
         if(!saveFile.exists()){
         	saveFile.mkdirs();
         }
         return saveFile;
    }
	
	/**
	 * @param args
	 */
	/*文件copy
	 * param src,des
	 * return ture 成功。false 失败
	 */
	public static boolean fileCopy(String src,String des){
		File srcFile=new File(src);
		File desFile=new File(des);
		byte[]b=new byte[1024];
		  try {
			  FileInputStream fis=new FileInputStream(srcFile);
			  FileOutputStream fos=new FileOutputStream(desFile,false);
			  while(true){
				  int i=fis.read(b);
				  if(i==-1)break;
				  fos.write(b,0,i);
			  }
			  fos.close();
			  fis.close();
			  return true;
		} catch (Exception e){ 
			e.printStackTrace();
		}
		return false;
	}
	
	/*
	 * 文件夹copy
	 * param src,des
	 *  return ture 成功。false 失败
	 * 
	 */
	
	public static boolean folderCopy(String src,String des){
		File srcFile=new File(src);
		File desFile=new File(des);
		File []files=srcFile.listFiles();
		boolean flag = false;
		if(!desFile.exists())desFile.mkdir();
		for(int i=0;i<files.length;i++){
			String path=files[i].getAbsolutePath(); 
			if(files[i].isDirectory()){
				File newFile=new File("path.replace(src,des)");
				if(!newFile.exists())newFile.mkdir();//不存在新建文件夹
				folderCopy(path,path.replace(src,des));
			}
			else
			  flag=fileCopy(path,path.replace(src,des));//文件复制函数
			}
		return flag;
	}
	/**
     * 将上传文件转为Workbook集合
     * @param request
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
        public static List<Workbook> fileToWorkbook(HttpServletRequest request) throws IllegalStateException, IOException{
            List<Workbook> list = new ArrayList<Workbook>();
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Iterator<String> ite = multipartRequest.getFileNames();
            while(ite.hasNext()){
                MultipartFile multipartFile = multipartRequest.getFile(ite.next()); 
                String fileName = multipartFile.getOriginalFilename();
                String base = request.getSession().getServletContext().getRealPath("/") + File.separator + "uploadedExcel";
                File file = new File(base);
                if(!file.exists()){
                    file.mkdirs();
                }
                String path=base + File.separator + fileName;
                File destFile = new File(path);
                multipartFile.transferTo(new File(path));
                Workbook wb = null;
                if (fileName.endsWith("xls")) {
                    wb = new HSSFWorkbook(new FileInputStream(destFile));
                } else if (fileName.endsWith("xlsx")) {
                    wb = new XSSFWorkbook(new FileInputStream(destFile));
                }
                list.add(wb);
            }
             return list;  
        }
}